/**
 * Regex Selector for jQuery © James Padolsey
 *
 * @param elem
 * @param index
 * @param match
 * @returns {boolean}
 */
$.expr[':'].regex = function (elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ? matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels, '')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
};

/**
 * Calculate the width of textual element
 *
 * @param text
 * @param font optional
 * @returns {*}
 */
$.fn.textWidth = function (text, font) {

    if (!$.fn.textWidth.fakeEl) {
        $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    }

    $.fn.textWidth.fakeEl.text(text || this.val() || this.text());

    if (font) {
        $.fn.textWidth.fakeEl.css('font', font || this.css('font'));
    }

    return $.fn.textWidth.fakeEl.width();
};

String.prototype.fillTemplate = function (context) {

    if (!context) context = {};

    var regEx = new RegExp("\\$\\{[^\\}]+\\}", "g");
    var lastIndex = 0;
    var result = [];

    var match = regEx.exec(this);

    while (match !== null) {

        result.push(this.substring(lastIndex, match.index));

        var reference = match[0];
        var key = reference.substring(2, reference.length - 1);

        var value;
        if (typeof context[key] !== 'undefined') {
            value = context[key];
        } else {
            value = reference;
        }

        result.push(value);

        lastIndex = regEx.lastIndex;
        match = regEx.exec(this);
    }

    result.push(this.substring(lastIndex, this.length));

    return result.join("");
};

function populateSelect(selector, data, width) {
    var $select = $(selector);
    $.each(data.options, function (i, e) {
        var $option = $('<option>');
        $option.text(e.name);
        $option.val(e.value);
        if (data.selected == i) {
            $option.prop("selected", true);
        }
        $select.append($option);
    });
    $select.selectmenu({
        width: width, change: function (event, data) {
            $select.val(data.item.value);
        }
    });
    $("#" + $select.attr("id") + "-button").css("vertical-align", "middle");
}

function getSelectData(selector) {
    var $select = $(selector);
    var data = {selected: 0, options: []};
    $select.children("option").each(function (i, e) {
        var $option = $(e);
        data.options.push({name: $option.text(), value: $option.val()});
    });
    data.selected = $select.prop("selectedIndex");
    return data;
}

function populateTextfield(selector, data) {
    $(selector)
        .css("vertical-align", "middle")
        .css("font-size", "13px")
        .css("font-weight", "bold")
        .css("height", "15px")
        .css("padding", "3px")
        .css("text-align", "left")
        .css("width", "240px")
        .val(data.text);
}

function getTextfieldData(selector) {
    return {text: $(selector).val()};
}

// Read/Write
function readFromFile() {

    var fsoeType = /* dialog */ false ? 'openFile' : 'openWritableFile';

    chrome.fileSystem.chooseEntry({type: fsoeType, accepts: [{extensions: ['html']}]}, function (fileEntry) {
        if (!fileEntry) {
            $("#OuptutText").html("User did not choose a file");
            return;
        }
        fileEntry.file(function (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                document.getElementById("HTMLFile").value = e.target.result;
            };
            reader.readAsText(file);
        });
    });
}

function writeToFile() {

    chrome.fileSystem.chooseEntry({type: 'saveFile', suggestedName: 'myfile.html'}, function (writableFileEntry) {
        writableFileEntry.createWriter(function (writer) {
            writer.onwriteend = function (e) {
                $("#OuptutText").html("Save complete!");
            };
            writer.write(new Blob([document.getElementById("HTMLFile").value], {type: 'text/plain'}));
        }, errorHandler);
    });
}